package com.yunhe.authority.service.authority.impl;

import com.yunhe.authority.domain.authority.Role;
import com.yunhe.authority.domain.authority.User;
import com.yunhe.authority.domain.company.Company;
import com.yunhe.authority.repository.authority.RoleRepository;
import com.yunhe.authority.repository.authority.impl.RoleDao;
import com.yunhe.authority.service.authority.CompanyRoleService;
import com.yunhe.authority.service.company.CompanyService;
import com.yunhe.authority.util.MyHeaderUtil;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.common.filter.ServerContextHolder;
import com.yunhe.common.model.PageParam;
import com.yunhe.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

/**
 * @author zhengbo
 * @date 2021/7/16 10:34
 */
@Service
@Slf4j
public class CompanyRoleServiceImpl implements CompanyRoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private MyHeaderUtil headerUtil;


    @Override
    public Role createRole(Long companyId, Role role)
            throws ArgumentErrorException, ObjectNotFoundException, UniqueConstraintsException {

        //判断角色编号、角色标题是否为空
        if (StringUtil.isEmpty(role.getTitle())) {
            throw new ArgumentErrorException("角色名不能为空");
        }

        Company company = companyService.findById(companyId);
        if (company == null) {
            throw new ObjectNotFoundException("未找到该企业");
        }

        //这边是带上企业的id进行查询重名
        Role existRole = roleRepository.findRoleByCompanyIdAndTitle(companyId, role.getTitle());
        if (existRole != null) {
            throw new UniqueConstraintsException(role.getTitle() + "已存在");
        }

        User user = headerUtil.getHeaderUser();
        if (user != null) {
            role.setCreator(user.getTitle());
        }

        role.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        Role newRole = roleRepository.save(role);

        roleRepository.bindCompany(newRole.getId(), companyId);
        return newRole;
    }

    @Override
    public Role updateRole(Long companyId, Role role)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        //判断角色编号、角色标题是否为空
        if (StringUtil.isEmpty(role.getTitle())) {
            throw new ArgumentErrorException("角色名不能为空");
        }

        Optional<Role> roleOptional = roleRepository.findById(role.getId());
        if (!roleOptional.isPresent()) {
            throw new ObjectNotFoundException("找不到ID为" + role.getId() + "的角色");
        }

        Company company = companyService.findById(companyId);
        if (company == null) {
            throw new ObjectNotFoundException("未找到该企业");
        }

        //这边是带上企业的id进行查询重名
        Role existRole = roleRepository.findRoleByCompanyIdAndTitle(companyId, role.getTitle());
        if (existRole != null && !existRole.getId().equals(role.getId())) {
            throw new UniqueConstraintsException(role.getTitle() + "已存在");
        }

        Role oldRole = roleOptional.get();
        if(oldRole.isInitRole()){
            throw new ArgumentErrorException("当前角色名为："+role.getTitle()+"的角色为后台管理平台初始化角色不能编辑！");
        }

        Optional.ofNullable(role.getActivity()).ifPresent(oldRole::setActivity);
        Optional.ofNullable(role.getName()).ifPresent(oldRole::setName);
        Optional.ofNullable(role.getTitle()).ifPresent(oldRole::setTitle);
        Optional.ofNullable(role.getDescription()).ifPresent(oldRole::setDescription);

        return roleRepository.save(oldRole);

    }

    @Override
    public Iterable<Role> findRolesByCompanyId(Long companyId) {
        return roleRepository.findRoleByCompanyId(companyId);
    }

    @Override
    public Page<Role> findRolesByCompanyIdForPage(Long companyId, String keywords, PageParam pageParam) {
        Page<Role> rolePage = roleDao.findRolesByCompanyId(companyId, keywords, pageParam);
        return rolePage;
    }

}
